package com.tcy.bigevent.controller;

import com.tcy.bigevent.pojo.Result;
import com.tcy.bigevent.pojo.User;
import com.tcy.bigevent.service.UserService;
import com.tcy.bigevent.utils.JwtUtil;
import com.tcy.bigevent.utils.Md5Util;
import com.tcy.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private  UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp="^\\S{5,16}") String username, @Pattern(regexp="^\\S{5,16}") String password) {
        System.out.println("service-register:"+username+":"+password);
        //1.查询用户是否存在
        User user = userService.findByUserName(username);
        if (user != null) {
            return Result.error("用户名被占用");
        }
        //2.注册
        userService.register(username, password);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp="^\\S{5,16}") String username, @Pattern(regexp="^\\S{5,16}") String password) {
        User user = userService.findByUserName(username);
        System.out.println("username:"+username);
        if (user == null) {
            return Result.error("用户名不存在");
        }
        if(user.getPassword().equals(Md5Util.getMD5String(password))){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);
            if(token != null) stringRedisTemplate.delete(token);
            stringRedisTemplate.opsForValue().set(token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> UserInfo(/*@RequestHeader(name="Authorization") String token*/) {
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        String username = (String)claims.get("username");
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String)claims.get("username");
        System.out.println("username: "+username);
        return Result.success(userService.findByUserName(username));
    }
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
//        User user1 = userService.findByUserName(user.getUsername());
//        if (user1 != null && user1.getId() != user.getId()) {
//            return Result.error("用户名被占用");
//        }
        System.out.println("controller-user:"+user);
        userService.update(user);
        return Result.success();
    }
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        System.out.println("controller-user:"+avatarUrl);
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader(name="Authorization") String token) {
        //1.参数校验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        if(oldPwd.equals(newPwd)){
            return Result.error("新密码不能与旧密码相同");
        }
        if(!rePwd.equals(newPwd)){
            return Result.error("两次输入的密码不一致");
        }
        Map<String, Object> claims = ThreadLocalUtil.get();

        String currentPwd = userService.findByUserName((String) claims.get("username")).getPassword();
        if(currentPwd.equals(Md5Util.getMD5String(oldPwd))){
            //2.修改密码
            userService.updatePwd(params.get("new_pwd"));

            stringRedisTemplate.delete(token);
            return Result.success();
        }else
            return Result.error("旧密码错误");
    }
}
